<template>
  <div class="category-page">
    <div class="container">
      <!-- 分类导航区 -->
      <div class="category-nav">
        <div 
          v-for="category in categories" 
          :key="category.id"
          class="nav-item"
          @mouseenter="showSub = category.id"
          @mouseleave="showSub = null"
        >
          {{ category.name }}
          <!-- 二级分类面板 -->
          <div 
            class="sub-panel"
            v-if="showSub === category.id"
            @mouseenter="showSub = category.id"
            @mouseleave="showSub = null"
          >
            <div 
              v-for="sub in category.children" 
              :key="sub.id"
              class="sub-item"
              @click="selectCategory(sub)"
            >
              {{ sub.name }}
            </div>
          </div>
        </div>
      </div>

      <!-- 商品展示区 -->
      <div class="product-area">
        <h2 class="current-category">{{ currentCategoryName || '全部商品' }}</h2>
        
        <!-- 商品列表 -->
        <div class="product-list">
          <div 
            v-for="product in displayedProducts" 
            :key="product.id"
            class="product-card"
            @click="goToProductDetail(product.id)"
          >
            <img :src="product.productMainImg" :alt="product.productName" class="product-img">
            <div class="product-info">
              <h3>{{ product.productName }}</h3>
              <div class="price">¥{{ product.productPrice }}</div>
              <div class="sales">已售{{ product.productSold }}件</div>
              <button class="add-cart" @click.stop="addToCart(product)">加入购物车</button>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div class="pagination">
          <button 
            @click="prevPage"
            :disabled="currentPage === 1"
          >上一页</button>
          <span>第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>
          <button 
            @click="nextPage"
            :disabled="currentPage >= totalPages"
          >下一页</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { productAPI } from '@/http'

const router = useRouter()

// 分类数据 - 根据要求调整
const categories = ref([
  {
    id: 1,
    name: '手机数码',
    children: [
      { id: 101, name: '手机' },
      { id: 102, name: '相机' },
      { id: 103, name: '手表' },
      { id: 104, name: '耳机' },
      { id: 105, name: '音箱' },
      { id: 106, name: '电子书' }
    ]
  },
  {
    id: 2,
    name: '电脑办公',
    children: [
      { id: 201, name: '笔记本电脑' },
      { id: 202, name: '台式电脑' },
      { id: 203, name: '办公设备' },
      { id: 204, name: '平板' }
    ]
  }
])

// 商品数据
const products = ref<Array<{
  id: number;
  productName: string;
  productBrand: string;
  productType: string;
  productPrice: number;
  productColor: string;
  productSize: string;
  productMainImg: string;
  productCount: number;
  productPoint: number;
  productArea: string;
  productSold: number;
  xx: string;
  yy: any;
  productVersion: any;
  productStatus: any;
}>>([])

// UI状态
const showSub = ref<number | null>(null)
const currentCategory = ref<{id: number, name: string} | null>(null)
const currentPage = ref(1)
const pageSize = ref(8) // 每页8个商品

// 获取商品数据
const fetchProducts = async () => {
  try {
    const response = await productAPI.getRandomProduct(100) // 获取足够多的商品用于分页
    products.value = response.data
  } catch (error) {
    console.error('获取商品数据失败:', error)
  }
}

// 计算当前分类名称
const currentCategoryName = computed(() => {
  if (!currentCategory.value) return null
  return categories.value
    .flatMap(c => c.children)
    .find(c => c.id === currentCategory.value?.id)?.name
})

// 计算显示的商品
const displayedProducts = computed(() => {
  // 如果没有选中分类，显示所有商品
  if (!currentCategory.value) {
    return paginate(products.value)
  }
  
  // 过滤出当前分类的商品
  const filtered = products.value.filter(
    p => p.productType === currentCategory.value?.name
  )
  
  return paginate(filtered)
})

// 计算总页数
const totalPages = computed(() => {
  const total = currentCategory.value 
    ? products.value.filter(p => p.productType === currentCategory.value?.name).length
    : products.value.length
  
  return Math.ceil(total / pageSize.value)
})

// 选择分类
const selectCategory = (category: {id: number, name: string}) => {
  currentCategory.value = category
  currentPage.value = 1 // 重置页码
}

// 分页方法
const paginate = (list: typeof products.value) => {
  const start = (currentPage.value - 1) * pageSize.value
  return list.slice(start, start + pageSize.value)
}

// 上一页
const prevPage = () => {
  if (currentPage.value > 1) currentPage.value--
}

// 下一页
const nextPage = () => {
  if (currentPage.value < totalPages.value) currentPage.value++
}

// 跳转到商品详情
const goToProductDetail = (id: number) => {
  router.push(`/product/${id}`)
}

// 加入购物车
const addToCart = (product: typeof products.value[0]) => {
  console.log('加入购物车:', product)
  // 这里可以添加购物车逻辑
}

// 页面加载时获取数据
onMounted(() => {
  fetchProducts()
})
</script>

<style scoped>
.category-page {
  font-family: 'Helvetica Neue', Arial, sans-serif;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.container {
  display: flex;
}

/* 分类导航样式 */
.category-nav {
  width: 200px;
  background: #f8f8f8;
  border-radius: 8px;
  padding: 15px 0;
}

.nav-item {
  padding: 12px 20px;
  cursor: pointer;
  position: relative;
  font-weight: 500;
  transition: all 0.2s;
}

.nav-item:hover {
  background: #f0f0f0;
  color: #ff6700;
}

/* 二级分类面板 */
.sub-panel {
  position: absolute;
  left: 200px;
  top: 0;
  width: 200px;
  background: white;
  box-shadow: 0 0 10px rgba(0,0,0,0.1);
  border-radius: 0 8px 8px 0;
  z-index: 10;
  padding: 10px 0;
}

.sub-item {
  padding: 10px 20px;
  cursor: pointer;
  transition: all 0.2s;
}

.sub-item:hover {
  background: #f5f5f5;
  color: #ff6700;
}

/* 商品展示区 */
.product-area {
  flex: 1;
  margin-left: 20px;
}

.current-category {
  font-size: 24px;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.product-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 20px;
}

.product-card {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
  transition: transform 0.3s, box-shadow 0.3s;
  cursor: pointer;
}

.product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0,0,0,0.1);
}

.product-img {
  width: 100%;
  height: 180px;
  object-fit: cover;
  border-bottom: 1px solid #f5f5f5;
}

.product-info {
  padding: 15px;
}

.product-info h3 {
  font-size: 16px;
  margin: 0 0 10px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.price {
  color: #ff6700;
  font-size: 18px;
  font-weight: bold;
  margin: 10px 0;
}

.sales {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.add-cart {
  width: 100%;
  padding: 8px 0;
  background: #ff6700;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background 0.3s;
}

.add-cart:hover {
  background: #f25807;
}

/* 分页样式 */
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 30px;
  padding: 20px 0;
}

.pagination button {
  padding: 8px 16px;
  margin: 0 10px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 4px;
  cursor: pointer;
}

.pagination button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.pagination button:not(:disabled):hover {
  border-color: #ff6700;
  color: #ff6700;
}

.pagination span {
  margin: 0 10px;
}
</style>